import React, {useState } from 'react'
import './index.scss'
import bg from'../../assets/bg.jpg'
import lgbg from '../../assets/lgbg.jpg'
import logo from'../../assets/logo.png'
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input} from 'antd';
import { login } from '../../api/users'
import { useDispatch } from 'react-redux'
import { setToken } from '../../store/modules/userStore'
import { useNavigate } from 'react-router-dom'

export default function Login() {
  //获取表单实例
  const [form] = Form.useForm()
  const dispatch=useDispatch()
  const navigator=useNavigate()
  //控制登录按钮是否处于请求中
  const[loading,setLoading] =useState<boolean>(false)
  const handleLogin=()=>{
    setLoading(true)
    //表单校验 validateFields()返回一个promise
    form.validateFields().
    then( async (value)=>{
      const {data:{data:{username,token}}}=await login({
        username:value.username,
        password:value.password
      }) 
      setLoading(false)
      sessionStorage.setItem('username',username)
      //将取到的token存到redux状态中
      dispatch(setToken(token))
      navigator('/',{replace:true})//替代掉原先的记录,这样使用浏览器的页面返回就不能返回
    }).catch((err)=>{
      setLoading(false)
      console.log(err);
    }) 
  }

  return (
    <div className="login" style={{backgroundImage:`url(${bg})`}}>
      <div className="lgbg" style={{backgroundImage:`url(${lgbg})`}}>
        <div className="loginInput">
            <div className="title">
              <div className="logo">
                <img src={`${logo}`} alt="" />
              </div>
              <h1>智慧园区管理平台</h1>
            </div>
          <Form
            form={form}
            name="login"
            initialValues={{ remember: false }}
            style={{ maxWidth: 360 }}
          >
            <Form.Item
              name="username"
              rules={[
                { required: true, message: '请输入正确用户名!'},
                { pattern: /^[a-zA-Z0-9]{3,9}$/, message: '用户名只能是3-9位字母和数字' },
              ]}
            >
              <Input prefix={<UserOutlined />} placeholder="用户名" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                { required: true, message: '请输入密码!'},
                { max:9,message:'密码长度不能超过9位'},
                { min:6,message:'密码长度不能小于6位'}
              ]}
            >
              <Input prefix={<LockOutlined />} type="password" placeholder="密码" />
            </Form.Item>
            <Form.Item>
              <Button block type="primary" htmlType="submit" 
              onClick={handleLogin}
              loading={loading}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  )
}
